import { Toast } from 'react-vant'
import { checked } from '../api';
const initialState = {
  list:[], //总数居
  copy_data:[], //拷贝数据
  sonList:[],  //子数据
  cangList:[],
  shopCart:JSON.parse(window.localStorage.getItem('shopCart')) ||[], //购物车数据
  allPrice:0,  //总价
  allCheked:false
}

export default (state = initialState, { type, payload }) => {
  const newState =JSON.parse(JSON.stringify(state));

  const set_localStorage =(name,data)=>{
    return window.localStorage.setItem(name,JSON.stringify(data))
  }

  const All_price = ()=>{
    let price = 0;
    newState.shopCart.forEach((item,index) =>{
      if(item.checked){
        console.log('ssss')
         price+=item.price * item.count
      }
    })
    console.log(price)
    newState.allPrice=price;
  }

  switch (type) {
    //获取总数居
  case "GET_LIST":
    newState.list=payload;
    newState.copy_data=payload;
    newState.sonList=payload[0].children;
    set_localStorage("sonList",newState.sonList)
    return newState
    //设置子数据
  case "C_INDEX":
   newState.sonList=newState.list[payload].children;
   newState.copy_data=newState.list[payload].children;
   set_localStorage("sonList",newState.sonList)
   return newState  
  //筛选数据  
  case "PAI":
    
      newState.sonList=newState.copy_data.sort((a,b)=>{
        if(payload=='b'){
          return b.price - a.price 
        }else{
          return a.price - b.price 
        }
      })
   
    return newState 
  //收藏数据  
  case "SHOU":
    newState.sonList.forEach((item) => {
      if(item.id == payload){
        item.liked = !item.liked;
        Toast.success({message:item.liked ?'收藏成功':"取消收藏"})
      }
    })

    return newState
  //加入购物车
  case "ADD_SHOP":
    //先看 购物车中有没有该数据
    const flag = newState.shopCart.some((item) => {
      return item.id == payload
    })
    //如果存在
    if(flag){
      //在购物车数据中的这条数据数量加+1
      newState.shopCart.forEach((item,ind) =>{
        if(item.id == payload){
          item.count++
        }
      })
    }else{
      newState.copy_data.forEach(item =>{
        if(item.id === payload){
          newState.shopCart.push(item);
          Toast.success('添加成功')
        }
      })
    }
    
    set_localStorage('shopCart',newState.shopCart)
    return newState
  case "CHECKED":
    newState.shopCart.forEach(item => {
        if(item.id ==payload.id){
          item.checked = !item.checked
          set_localStorage('shopCart',newState.shopCart)
        }
    });
    All_price()
    newState.allCheked =newState.shopCart.every((item) => item.checked )
    return newState
  case 'ALL_CHECKED':
    newState.allCheked=payload;
    newState.shopCart.forEach((item,index)=>{
        item.checked =payload;
        set_localStorage('shopCart',newState.shopCart)
    })
    All_price();
    
  default:
    return newState
  }
}
